package com.example.java_gobang.game;

import com.example.java_gobang.model.User;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: LXW
 * Date: 2022-08-06
 * Time: 14:50
 */
@Component
public class RoomManager {
    // key 为 roomId, value 为一个 Room 对象
    private ConcurrentHashMap<String, Room> rooms = new ConcurrentHashMap<>();
    private ConcurrentHashMap<Integer, String> userIdToRoomId = new ConcurrentHashMap<>();

    /**
     * 将两个用户放进同一个房间
     * @param room
     * @param userId1
     * @param userId2
     */
    public void add(Room room, int userId1, int userId2) {
        rooms.put(room.getRoomId(), room);
        userIdToRoomId.put(userId1, room.getRoomId());
        userIdToRoomId.put(userId2, room.getRoomId());
    }

    /**
     * 将俩个用户移除出房间
     * @param roomId
     * @param userId1
     * @param userId2
     */
    public void remove(String roomId, int userId1, int userId2) {
        rooms.remove(roomId);
        userIdToRoomId.remove(userId1);
        userIdToRoomId.remove(userId2);
    }

    /**
     * 根据roomId找到指定房间
     * @param roomId
     * @return
     */
    public Room getRoomByRoomId(String roomId) {
        return rooms.get(roomId);
    }

    /**
     * 根据userId找到对应房间
     * @param userId
     * @return
     */
    public Room getRoomByUserId(int userId) {
        // 1.先根据userId获得roomId
        String roomId = userIdToRoomId.get(userId);
        if (roomId == null) {
            // userId -> roomId 映射关系不存在, 直接返回 null
            return null;
        }
        // 2.再通过roomId找到指定房间
        return rooms.get(roomId);
    }
}
